<template>
  <div class="threshold-management">
    <h2>阈值管理</h2>
    <el-button type="primary" @click="openAddDialog">添加</el-button>

    <el-table :data="thresholds" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="name" label="名称" width="120" align="center" />
      <el-table-column prop="number" label="阈值" width="120" align="center" />
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button type="primary" @click="openEditDialog(scope.row)">修改</el-button>
          <el-button type="danger" @click="deleteThreshold(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加阈值' : '修改阈值'" width="400px">
      <el-form :model="form" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="阈值">
          <el-input-number v-model="form.number" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveThreshold">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { post } from '@/api/api';

const thresholds = ref([]);
const dialogVisible = ref(false);
const dialogType = ref('add');
const form = ref({ id: null, name: '', number: 0 });

// 获取阈值列表
const fetchThresholds = async () => {
  const res = await post('/threshold/selectThresholdList');
  if (res && res.data) {
    thresholds.value = res.data;
  }
};

// 打开添加对话框
const openAddDialog = () => {
  dialogType.value = 'add';
  form.value = { id: null, name: '', number: 0 };
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row) => {
  dialogType.value = 'edit';
  form.value = { ...row };
  dialogVisible.value = true;
};

// 保存阈值
const saveThreshold = async () => {
  const url = dialogType.value === 'add' ? '/threshold/insertThreshold' : '/threshold/updateThresholdById';
  const res = await post(url, form.value);
  if (res) {
    ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功');
    dialogVisible.value = false;
    fetchThresholds();
  }
};

// 删除阈值
const deleteThreshold = async (id) => {
  const res = await post('/threshold/deleteThresholdById', { id });
  if (res) {
    ElMessage.success('删除成功');
    fetchThresholds();
  }
};

onMounted(() => {
  fetchThresholds();
});
</script>

<style scoped>
.threshold-management {
  padding: 20px;
}
</style>